package com.lipiao.nb_iot;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;


import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;

import java.util.Objects;

public class Person_Activity extends AppCompatActivity {
    public Button save;
    public Button fire;
    public Cursor cursor;
    public String phoneNum = null;
    public String contactName = null;

    public ImageView phone_2,phone_3,phone_4,phone_5,phone_6,phone_7,phone_8;
    public ImageView add_1,add_2,add_3,add_4,add_5,add_6,add_7;
    public int flag=0;
    public Vibrator vibrator;
    public EditText friend_1,friend_2,friend_3,friend_4,friend_5,friend_6,user,boss;
    public EditText text_1,text_2,text_3,text_4,text_5,text_6,text_7;
    public SharedPreferences pref;
    public MediaPlayer mMediaPlayer;
    public SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_);

        //**版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取**
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //ContextCompat.checkSelfPermission() 方法 指定context和某个权限 返回PackageManager.PERMISSION_DENIED或者PackageManager.PERMISSION_GRANTED
            if (ContextCompat.checkSelfPermission(Person_Activity.this, android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                // 若不为GRANTED(即为DENIED)则要申请权限了
                // 申请权限 第一个为context 第二个可以指定多个请求的权限 第三个参数为请求码
                ActivityCompat.requestPermissions(Person_Activity.this, new String[]{android.Manifest.permission.READ_CONTACTS}, 1);
            } else {
                //权限已经被授予，在这里直接写要执行的相应方法即可
                //intentToContact();
            }
        }else {
            // 低于6.0的手机直接访问
            //intentToContact();
        }
        initView();
        initListener();
        start();
    }

    class OnClick implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.phone_2:callPhone(boss.getText().toString());break;
                case R.id.phone_3:callPhone(friend_1.getText().toString());break;
                case R.id.phone_4:callPhone(friend_2.getText().toString());break;
                case R.id.phone_5:callPhone(friend_3.getText().toString());break;
                case R.id.phone_6:callPhone(friend_4.getText().toString());break;
                case R.id.phone_7:callPhone(friend_5.getText().toString());break;
                case R.id.phone_8:callPhone(friend_6.getText().toString());break;
                case R.id.add_1:intentToContact(); text_1.setText(contactName);boss.setText(phoneNum);break;
                case R.id.add_2:intentToContact(); text_2.setText(contactName);friend_1.setText(phoneNum);break;
                case R.id.add_3:intentToContact(); text_3.setText(contactName);friend_2.setText(phoneNum);break;
                case R.id.add_4:intentToContact(); text_4.setText(contactName);friend_3.setText(phoneNum);break;
                case R.id.add_5:intentToContact(); text_5.setText(contactName);friend_4.setText(phoneNum);break;
                case R.id.add_6:intentToContact(); text_6.setText(contactName);friend_5.setText(phoneNum);break;
                case R.id.add_7:intentToContact(); text_7.setText(contactName);friend_6.setText(phoneNum);break;
            }
        }
    }

    private void initView() {
        save=findViewById(R.id.save);
        friend_1=findViewById(R.id.friend_1);
        friend_2=findViewById(R.id.friend_2);
        friend_3=findViewById(R.id.friend_3);
        friend_4=findViewById(R.id.friend_4);
        friend_5=findViewById(R.id.friend_5);
        friend_6=findViewById(R.id.friend_6);
        user=findViewById(R.id.user);
        boss=findViewById(R.id.boss);

        text_1=findViewById(R.id.text_1);
        text_2=findViewById(R.id.text_2);
        text_3=findViewById(R.id.text_3);
        text_4=findViewById(R.id.text_4);
        text_5=findViewById(R.id.text_5);
        text_6=findViewById(R.id.text_6);
        text_7=findViewById(R.id.text_7);

        add_1=findViewById(R.id.add_1);
        add_2=findViewById(R.id.add_2);
        add_3=findViewById(R.id.add_3);
        add_4=findViewById(R.id.add_4);
        add_5=findViewById(R.id.add_5);
        add_6=findViewById(R.id.add_6);
        add_7=findViewById(R.id.add_7);

        fire=findViewById(R.id.fire);
        phone_2=findViewById(R.id.phone_2);
        phone_3=findViewById(R.id.phone_3);
        phone_4=findViewById(R.id.phone_4);
        phone_5=findViewById(R.id.phone_5);
        phone_6=findViewById(R.id.phone_6);
        phone_7=findViewById(R.id.phone_7);
        phone_8=findViewById(R.id.phone_8);

        phone_2.setOnClickListener(new OnClick());
        phone_3.setOnClickListener(new OnClick());
        phone_4.setOnClickListener(new OnClick());
        phone_5.setOnClickListener(new OnClick());
        phone_6.setOnClickListener(new OnClick());
        phone_7.setOnClickListener(new OnClick());
        phone_8.setOnClickListener(new OnClick());

        add_1.setOnClickListener(new OnClick());
        add_2.setOnClickListener(new OnClick());
        add_3.setOnClickListener(new OnClick());
        add_4.setOnClickListener(new OnClick());
        add_5.setOnClickListener(new OnClick());
        add_6.setOnClickListener(new OnClick());
        add_7.setOnClickListener(new OnClick());

        pref=Objects.requireNonNull(getSharedPreferences("data", Context.MODE_PRIVATE));
        boolean isRemember=pref.getBoolean("result",false);
        if(isRemember){
            friend_1.setText(pref.getString("num_1",""));
            friend_2.setText(pref.getString("num_2",""));
            friend_3.setText(pref.getString("num_3",""));
            friend_4.setText(pref.getString("num_4",""));
            friend_5.setText(pref.getString("num_5",""));
            friend_6.setText(pref.getString("num_6",""));

            text_1.setText(pref.getString("text_1",""));
            text_2.setText(pref.getString("text_2",""));
            text_3.setText(pref.getString("text_3",""));
            text_4.setText(pref.getString("text_4",""));
            text_5.setText(pref.getString("text_5",""));
            text_6.setText(pref.getString("text_6",""));
            text_7.setText(pref.getString("text_7",""));

            user.setText(pref.getString("user",""));
            boss.setText(pref.getString("boss",""));
        }
    }

//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        //重载，进行自定义：获取statusFragment中的信息
//        if (getUserVisibleHint()==true) {
//            Log.d("碎片2", "从fragment1中获取的值" + StatusFragment.getTemperature());
//            start();
//        }
//    }

    public void start(){
        Log.d("数据成功!","");
        String[] tel=new String[7];
        tel[1]=friend_1.getText().toString();
        tel[2]=friend_2.getText().toString();
        tel[3]=friend_3.getText().toString();
        tel[4]=friend_4.getText().toString();
        tel[5]=friend_5.getText().toString();
        tel[6]=friend_6.getText().toString();

        if(StatusFragment.getTemperature()>80){
            //手机震动
            vibrator = (Vibrator)Objects.requireNonNull((getSystemService(VIBRATOR_SERVICE)));
            vibrator.vibrate(1000*1000);
            Log.d("我震动了","哈哈哈");
            //发出警报声
            mMediaPlayer=MediaPlayer.create(Person_Activity.this, R.raw.fire);
            mMediaPlayer.start();
            flag=1;
            Log.d("我发出了警报声","哈哈哈");
            //给业主发送报警信息
            String url_1 = "http://v.juhe.cn/sms/send?mobile=" + pref.getString("user","") + "&tpl_id=" + "147142" + "&tpl_value=%23code%23%3D654654&key=" + "d1672932a1821de9c037577a08fa4bc4";
            RxVolley.get(url_1, new HttpCallback() {
                @Override
                public void onSuccess(String t) {
                    Toast.makeText(Person_Activity.this, "短信发送成功~", Toast.LENGTH_SHORT).show();
                }
            });
            //给物业发送报警信息
            String url_2 = "http://v.juhe.cn/sms/send?mobile=" + pref.getString("boss","") + "&tpl_id=" + "146833" + "&tpl_value=%23code%23%3D654654&key=" + "d1672932a1821de9c037577a08fa4bc4";
            RxVolley.get(url_2, new HttpCallback() {});

            //给用户好友发送短信
            for(int i=1;i<=6;i++) {
                String url_3 = "http://v.juhe.cn/sms/send?mobile=" + tel[i] + "&tpl_id=" + "147144" + "&tpl_value=%23code%23%3D654654&key=" + "d1672932a1821de9c037577a08fa4bc4";
                RxVolley.get(url_3, new HttpCallback() {});
            }
        }
    }

    private void initListener() {
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = pref.edit();
                editor.putString("num_1", friend_1.getText().toString());
                editor.putString("num_2", friend_2.getText().toString());
                editor.putString("num_3", friend_3.getText().toString());
                editor.putString("num_4", friend_4.getText().toString());
                editor.putString("num_5", friend_5.getText().toString());
                editor.putString("num_6", friend_6.getText().toString());

                editor.putString("text_1", text_1.getText().toString());
                editor.putString("text_2", text_2.getText().toString());
                editor.putString("text_3", text_3.getText().toString());
                editor.putString("text_4", text_4.getText().toString());
                editor.putString("text_5", text_5.getText().toString());
                editor.putString("text_6", text_6.getText().toString());
                editor.putString("text_7", text_7.getText().toString());

                editor.putString("user", user.getText().toString());
                editor.putString("boss", boss.getText().toString());
                editor.putBoolean("result",true);
                Log.d("数据调试",pref.getInt("progress",1)+"");
                Toast.makeText(Person_Activity.this,"保存成功~",Toast.LENGTH_SHORT).show();
                editor.apply();
            }
        });

        fire.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(flag==1){
                    mMediaPlayer.stop();
                    vibrator.cancel();
                }
            }
        });
    }

    @SuppressLint("MissingPermission")
    private void callPhone(String numner) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri uri = Uri.parse("tel:" + numner);
        intent.setData(uri);
        startActivity(intent);
    }

    // 用户权限 申请 的回调方法
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if(requestCode== 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                intentToContact();
            } else {
                Toast.makeText(Person_Activity.this,"授权被禁止",Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void intentToContact() {
        // 跳转到联系人界面
        Intent intent = new Intent();
        intent.setAction("android.intent.action.PICK");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setType("vnd.android.cursor.dir/phone_v2");
        startActivityForResult(intent, 0x30);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0x30) {
            if (data != null) {
                Uri uri = data.getData();
                // 创建内容解析者
                ContentResolver contentResolver = getContentResolver();
                cursor = null;
                if (uri != null) {
                    cursor = contentResolver.query(uri,
                            new String[]{"display_name","data1"}, null, null, null);
                }
                assert cursor != null;
                while (cursor.moveToNext()) {
                    contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    phoneNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                cursor.close();
            }
        }
    }
}
